package com.xs.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xs.common.JsonResult;
import com.xs.entity.Article;
import com.xs.entity.User;
import com.xs.entity.utils.CountAndDayCount;
import com.xs.service.ArticleService;
import com.xs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2022-08-22 16:42:37
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ArticleService articleService;


    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("/regist")
    public JsonResult<?> regist(@RequestBody User user) {
        //判断账号是否存在
        User row = userService.getOne(Wrappers.<User>lambdaQuery().
                eq(User::getUsername, user.getUsername()));
        if (row!=null){
            return JsonResult.success("-1","用户名 已存在请重新输入");
        }
        user.setCreateTime(new Date());
        //新增数据
        userService.save(user);
        return JsonResult.success();
    }

    /**
     * 后台登录
     * @param user
     * @return
     */
    @PostMapping("/adminlogin")
    public JsonResult<?> adminlogin(@RequestBody User user) {
        User row = userService.getOne(Wrappers.<User>lambdaQuery().
                eq(User::getUsername, user.getUsername()).
                eq(User::getPassword, user.getPassword()));
        if (row==null){
            return JsonResult.success("-1","用户名或密码错误");
        }else if (row.getCover()!=1){
            return JsonResult.success("-1","您的账号非管理员账号");
        }
        return JsonResult.success(row);
    }


    /**
     * 前台登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public JsonResult<?> login(@RequestBody User user) {
        User row = userService.getOne(Wrappers.<User>lambdaQuery().
                eq(User::getUsername, user.getUsername()).
                eq(User::getPassword, user.getPassword()));
        if (row==null){
            return JsonResult.success("-1","用户名或密码错误");
        }
        return JsonResult.success(row);
    }

    /**
     * 新增数据
     *
     * @param user 实体
     * @return 新增结果
     */
    @PostMapping
    public JsonResult<?> add(@RequestBody User user) {
        System.out.println(user);
        if (user.getPassword()==null){
            user.setPassword("123456");
        }else if (user.getPassword().length()<6){
            return JsonResult.success("-1","账号密码不能小于6位");
        }else if (user.getNickName()==null){
            user.setNickName("新用户");
        }
        user.setCreateTime(new Date());
        userService.save(user);
        return JsonResult.success();
    }


    /**
     * 分页查询普通用户
     * @return
     */
    @GetMapping
    public JsonResult<?> add(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "") String search) {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("cover",0);
        if (search!=null){
            wrapper.like("nick_name",search);
        }

        return JsonResult.success( userService.page(new Page<>(pageNum, pageSize),wrapper));
    }

    /**
     * 分页查询管理员
     * @return
     */
    @GetMapping("/selectadmin")
    public JsonResult<?> getAdmin(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam(defaultValue = "") String search) {
        QueryWrapper<User> wrapper= new QueryWrapper<User>();
        wrapper.like("nick_name",search);
        wrapper.eq("cover",1);
        return JsonResult.success(userService.page(new Page<>(pageNum,pageSize),wrapper));
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @PutMapping
    public JsonResult<?> update(@RequestBody User user) {
        if (user.getPassword().length()<6){
            return JsonResult.success("-1","账号密码不能小于6位");
        }
        userService.updateById(user);
        return JsonResult.success();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteByid(@PathVariable Integer id){
        userService.removeById(id);
        return JsonResult.success();
    }


    @GetMapping("/{id}")
    public JsonResult<?> getById(@PathVariable Integer id){
        return JsonResult.success(userService.getById(id));
    }


    //查询文章数量
    @GetMapping("/PersonalCenter/{id}")
    public JsonResult<?> getConte(@PathVariable Integer id){
        User user = userService.getById(id);
        //查询文章数量
        QueryWrapper<Article> wrapper=new QueryWrapper<>();
        wrapper.eq("uid",id);
        int count = articleService.count(wrapper);
        user.setCount(count);
        return JsonResult.success(user);
    }

    //推荐作者
    @GetMapping("/recommandUser")
    public  JsonResult<?> recommandUser(){
        return JsonResult.success(userService.recommandUser());
    }

    //查询阅读量
    @GetMapping("/findReadNumber/{id}")
    public JsonResult<?> findReadNumber(@PathVariable("id") Integer id){
        return JsonResult.success(userService.findReadNumber(id));
    }

    //查询收藏量
    @GetMapping("/findCollectionNumber/{id}")
    public JsonResult<?> findCollectionNumber(@PathVariable("id") Integer id){
        return JsonResult.success(userService.findCollectionNumber(id));
    }


    //通过文章的作者id名称拿到作者的全部信息
    @GetMapping("/findUserInfor/{aid}")
    public JsonResult<?> findUserByArticle_user(@PathVariable Integer aid){
        User user = userService.UserDataFindByArticle(aid);
        return JsonResult.success(user);
    }





    //获取当日注册用户的数量
    //以及用户的总数据
    @GetMapping("/count")
    public JsonResult<?> countUser() throws ParseException {


        //获取总的信息
        List<User> row = userService.list();
        List<String> time=new ArrayList<>();
        //创建时间转换器
        DateFormat df = new SimpleDateFormat("YYYY-MM-dd");
        for (User user : row) {
            String format = df.format(user.getCreateTime());
            time.add(format);
        }
        System.out.println(time);
        Date date = new Date();
        //获取当前时间的年月日
        String data = df.format(date);
        int count=0;

        for (String s : time) {
            if (s.equals(data)){
                count=count+1;
            }
        }

        //将数据打包
        CountAndDayCount rows=new CountAndDayCount();
        rows.setCount(userService.count());
        rows.setDayCount(count);
        return JsonResult.success(rows);
    }
}

